package com.mantru.iotpot.dishes;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.ManualCookActivity;
import com.mantru.iotpot.Cook.SetOilPumpActivity;
import com.mantru.iotpot.Cook.ThrowVegetablesActivity;
import com.mantru.iotpot.DateClass.BoxDate;
import com.mantru.iotpot.DateClass.Handing_Config;
import com.mantru.iotpot.MakeSeekBar;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.DishesRecordEvent;
import com.mantru.iotpot.eventbus.EventMessage;
import com.mantru.iotpot.eventbus.RefreshEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class DishesRecordActivity extends AppCompatActivity implements View.OnClickListener , View.OnLongClickListener{
    private ApplicationClass ac;
    private SeekBar seekBar1;
    private MakeSeekBar customSeekBar;
    private LinearLayout back;
    private Button star_record;
    private Button rotation1;
    private Button rotation2;
    private Button rotation3;
    private TextView name1;
    private TextView name2;
    private TextView name3;
    private TextView name4;
    private TextView name5;
    private TextView name6;
    private TextView text1;
    private TextView text2;
    private TextView text3;
    private TextView text4;
    private TextView text5;
    private TextView text6;
    private List<Handing_Config> list = new ArrayList<>();
    private Handler handler = new Handler(); ; // 用于定时任务
    private AlertDialog dialog; // 用于存储弹窗对象
    private Runnable runnable; // 用于计时器逻辑
    private int progress1 = 0;//火力挡位 0-9档
    private int progress2 = 0;//转速 0-5档
    private int position = 1;//机械臂位置 1放下、2抬起
    private int rotation = 0;//揽拌子转向：0顺时针、1逆时针、2正反转
    private ImageView img1;
    private ImageView img2;
    private ImageView img3;
    private ImageView img4;
    private Button box1;
    private Button box2;
    private Button box3;
    private Button box4;
    private int selectbox = 1;
    private LinearLayout way1;
    private LinearLayout way2;
    private LinearLayout way3;
    private LinearLayout way4;
    private LinearLayout way5;
    private LinearLayout way6;
    private Button putfood;
    private Button restbox;
    private LinearLayout locks;
    private ImageView jiantou;
    private TextView lock_text1;
    private TextView lock_text2;
    private ImageView background;
    private View.OnTouchListener touchListener;
    private View.OnTouchListener sontouchListener;
    private CountDownTimer timer;
    private ImageView lockBackground;
    private LinearLayout end_record;
    private TextView record_time;
    private Handler timerHandler = new Handler();
    private Runnable timerRunnable;
    private int seconds = 0;//录制时间
    private String vegetable_name = "岑哥炒虾"; //菜谱名称
    private String face_image_url = "file:///data/data/com.mantru.iotpot/files/v001.png"; //默认的封面图的本地缓存的全路径
    private String vegetable_copies_qty = "1"; //份数，>=1
    private String vegetable_weight = "500";//重量，单位：克，>=1
    private List<BoxDate> boxDates = new ArrayList<>();//料盒参数
    private JSONObject root;//录制用到的json
    private TextView record_name;
    private TextView record_num;
    private Button wendu;
    private ColorStateList normalColor;
    private ColorStateList minColor;
    private Button error;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dishes_record);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        normalColor = ContextCompat.getColorStateList(DishesRecordActivity.this, R.color.normal_seekbar_color); // 正常颜色
        minColor = ContextCompat.getColorStateList(DishesRecordActivity.this, R.color.min_seekbar_color);// 最小值颜色
        ac.SaveSQLData_Handing_Config_Box(1, 1, 1, 1, 2);
        boolean result1 = ac.SaveSQLData_Handing_Config_Nozzle_Entity(4,0,0,0,0,0,0,0,0,0,0,0,2);
        result1 = ac.SaveSQLData_Handing_Config_Nozzle_Entity(5,0,0,0,0,0,0,0,0,0,0,0,2);
        result1 = ac.SaveSQLData_Handing_Config_Nozzle_Entity(6,0,0,0,0,0,0,0,0,0,0,0,2);
        // 获取 R.drawable.photo1 的文件路径
        String photoPath = getDrawablePathFromInternalStorage(R.drawable.photo1);
        if (photoPath != null) {
            face_image_url = photoPath; // 赋值给 face_image_url
            Log.d("PhotoPath", "Photo path: " + face_image_url);
        } else {
            Log.e("PhotoPath", "Failed to get photo path");
            // 设置一个默认值或进行其他处理
            face_image_url = "file:///data/data/com.mantru.iotpot/files/v001.png";
        }
        boolean result = ac.Handing_Start();
        Log.d("ManualCookActivity","result: " + result);
        initialization(); // 初始化按钮
        getJson(); // 获取json数据
        vegetable_name = getIntent().getStringExtra("food_name");
        vegetable_copies_qty = getIntent().getStringExtra("food_num");
        record_name.setText(vegetable_name);
        record_num.setText(vegetable_copies_qty + "份");
        setBoxDates();//对料盒数据初始化
        Log.d("getJson", "json_data获取成功");
        setview(); // 设置控件文本
        if (result){
            cheak(); // 初始化状态
            Log.d("ManualCookActivity","cheak完成");
            startcheak(); // 定时任务
        }
    }


    public void initialization(){
        seekBar1 = findViewById(R.id.disher_record_seekBar1);
        customSeekBar = findViewById(R.id.disher_record_seekbar2);
        back = findViewById(R.id.disher_record_work_back);
        wendu = findViewById(R.id.disher_record_work_wendu);
        star_record = findViewById(R.id.disher_record_work_button1);//开始录制
        end_record = findViewById(R.id.disher_record_work_button2);//结束录制
        record_time = findViewById(R.id.disher_record_work_button2_time);//录制时间
        record_name = findViewById(R.id.disher_record_food_name); //菜谱名称
        record_num = findViewById(R.id.disher_record_cook_num);//份数
        error = findViewById(R.id.disher_record_work_error);

        rotation1 = findViewById(R.id.disher_record_way_rotation1);//搅拌方向
        rotation2 = findViewById(R.id.disher_record_way_rotation2);
        rotation3 = findViewById(R.id.disher_record_way_rotation3);
        name1 = findViewById(R.id.disher_record_way_name1);//组合名字
        name2 = findViewById(R.id.disher_record_way_name2);
        name3 = findViewById(R.id.disher_record_way_name3);
        name4 = findViewById(R.id.disher_record_way_name4);
        name5 = findViewById(R.id.disher_record_way_name5);
        name6 = findViewById(R.id.disher_record_way_name6);
        text1 = findViewById(R.id.disher_record_way_text1);//组合内容
        text2 = findViewById(R.id.disher_record_way_text2);
        text3 = findViewById(R.id.disher_record_way_text3);
        text4 = findViewById(R.id.disher_record_way_text4);
        text5 = findViewById(R.id.disher_record_way_text5);
        text6 = findViewById(R.id.disher_record_way_text6);
        img1 = findViewById(R.id.disher_record_work_img1);//料盒投发图片
        img2 = findViewById(R.id.disher_record_work_img3);
        img3 = findViewById(R.id.disher_record_work_img5);
        img4 = findViewById(R.id.disher_record_work_img7);
        box1 = findViewById(R.id.disher_record_cook_box1);//料盒投放按钮
        box2 = findViewById(R.id.disher_record_cook_box2);
        box3 = findViewById(R.id.disher_record_cook_box3);
        box4 = findViewById(R.id.disher_record_cook_box4);
        way1 = findViewById(R.id.disher_record_way1);//组合按钮
        way2 = findViewById(R.id.disher_record_way2);
        way3 = findViewById(R.id.disher_record_way3);
        way4 = findViewById(R.id.disher_record_way4);
        way5 = findViewById(R.id.disher_record_way5);
        way6 = findViewById(R.id.disher_record_way6);
        putfood = findViewById(R.id.disher_record_putfood);
        restbox = findViewById(R.id.disher_record_ResetBox);
        locks = findViewById(R.id.disher_record_work_locks);
        jiantou = findViewById(R.id.disher_record_jiantou);
        lock_text1 = findViewById(R.id.disher_record_lock_text1);
        lock_text2 = findViewById(R.id.disher_record_lock_text2);
        background = findViewById(R.id.disher_record_background);
        lockBackground = findViewById(R.id.disher_record_lock_background);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//火力
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // progress参数即为当前的进度值
                if (progress < 1) {
                    progress = 1; // 设置最小值为1
                    seekBar1.setProgress(1);
                }
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.setProgressTintList(minColor); // 设置为最小值颜色
                } else {
                    seekBar.setProgressTintList(normalColor); // 设置为正常颜色
                }
                progress1 = progress - 1;
                Log.d("progress","progress1: " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动时的操作
                ac.Handing_Setting_Fire(progress1);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时的操作
                ac.Handing_Setting_Fire(progress1);
            }
        });
        customSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//转速
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress < 1) {
                    progress = 1; // 设置最小值为1
                    customSeekBar.setProgress(1);
                }
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.setProgressTintList(minColor); // 设置为最小值颜色
                } else {
                    seekBar.setProgressTintList(normalColor); // 设置为正常颜色
                }
                progress2 = progress - 1;
                Log.d("progress","progress2: " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                ac.Handing_Setting_Gripper(position, rotation, progress2);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                ac.Handing_Setting_Gripper(position, rotation, progress2);
            }
        });
        back.setOnClickListener(this);
        rotation1.setOnClickListener(this);//搅拌爪方向
        rotation2.setOnClickListener(this);
        rotation3.setOnClickListener(this);
        box1.setOnClickListener(this);//料盒
        box2.setOnClickListener(this);
        box3.setOnClickListener(this);
        box4.setOnClickListener(this);
        way1.setOnClickListener(this);
        way2.setOnClickListener(this);
        way3.setOnClickListener(this);
        way4.setOnClickListener(this);
        way5.setOnClickListener(this);
        way6.setOnClickListener(this);
        putfood.setOnClickListener(this);
        restbox.setOnClickListener(this);
        locks.setOnClickListener(this);
        way1.setOnLongClickListener(this);//长按事件
        way2.setOnLongClickListener(this);
        way3.setOnLongClickListener(this);
        way4.setOnLongClickListener(this);
        way5.setOnLongClickListener(this);
        way6.setOnLongClickListener(this);
        star_record.setOnClickListener(this);
        end_record.setOnClickListener(this);
    }

    public void getJson(){//获取json数据
        String json_data = ac.GetSQLData_Handing_Config(2);
        Log.d("getJson","json_data: " + json_data);
        try {
            // 将字符串转换为 JSONObject
            JSONObject jsonObject = new JSONObject(json_data);
            boolean success = jsonObject.getBoolean("success");
            int itemCount = jsonObject.getInt("item_count");
            JSONArray itemData = jsonObject.getJSONArray("item_data");
            Log.d("getJson", "success: " + success);
            Log.d("getJson", "item_count: " + itemCount);
            // 遍历 item_data 数组
            for (int i = 0; i < itemData.length(); i++) {
                JSONObject item = itemData.getJSONObject(i);
                String configId = item.getString("config_id");
                String name = item.getString("name");
                String text = item.getString("text");
                Log.d("getJson", "item " + i + " - config_id: " + configId);
                Log.d("getJson", "item " + i + " - name: " + name);
                Log.d("getJson", "item " + i + " - text: " + text);
                list.add(new Handing_Config(configId,name,text));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("JSONParse", "Error parsing JSON: " + e.getMessage());
        }
    }
    //设置喷泵内的文本
    public void setview() {
        for (Handing_Config handingConfig : list) {
            String configId = handingConfig.getConfig_id();
            String name = handingConfig.getName();
            String text = handingConfig.getText();
            Log.d("Handing_Config","text: " + text);
            // 处理 text 字段，将 / 替换为换行符，并限制显示最多三行
            SpannableString processedText = processText(text);
            if (configId.equals("1")) {
                Log.d("text1","text1: " + text);
                name1.setText(name);
                text1.setText(text);
            } else if (configId.equals("2")) {
                name2.setText(name);
                text2.setText(text);
            } else if (configId.equals("3")) {
                name3.setText(name);
                text3.setText(text);
            } else if (configId.equals("4")) {
                name4.setText(name);
                text4.setText(processedText);
            } else if (configId.equals("5")) {
                name5.setText(name);
                text5.setText(processedText);
            } else if (configId.equals("6")) {
                name6.setText(name);
                text6.setText(processedText);
            }
        }
    }
    private SpannableString processText(String text) {
        // 将 / 替换为换行符
        String replacedText = text.replace("/", "\n");
        // 按换行符分割
        String[] lines = replacedText.split("\n");
        // 如果行数超过 3 行，截取前 3 行并添加省略号
        if (lines.length > 3) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 3; i++) {
                sb.append(lines[i]).append("\n");
            }
            sb.append("...");
            replacedText = sb.toString();
        }
        // 创建 SpannableString
        SpannableString spannableString = new SpannableString(replacedText);
        // 设置每一行居中对齐
        spannableString.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.disher_record_work_back){//返回按钮
            back.setBackgroundResource(R.drawable.button13);
            // 返回按钮
            String title = "询问";
            String content = "确认要终止炒菜吗？";
            tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                @Override
                public void onConfirmClick() {
                    // 点击确认按钮后的逻辑
//                    Toast.makeText(DishesRecordActivity.this, "确认", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(DishesRecordActivity.this, "确认");
                    back.setBackgroundResource(R.drawable.button11);
                    ac.Handing_Stop();
                    finish();
                }
                @Override
                public void onCancelClick() {
                    // 点击取消按钮后的逻辑
//                    Toast.makeText(DishesRecordActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(DishesRecordActivity.this, "取消");
                    back.setBackgroundResource(R.drawable.button11);
                }
            });
        } else if (v.getId() == R.id.disher_record_way_rotation1) {//揽拌子转向：0正方向、1反方向、2周期正反转
            rotation = 0;
            ac.Handing_Setting_Gripper(position, rotation, progress2);
            cleanbutton(1);
            rotation1.setBackgroundResource(R.drawable.button13);
        }else if (v.getId() == R.id.disher_record_way_rotation2) {//揽拌子转向：0正方向、1反方向、2周期正反转
            rotation = 1;
            ac.Handing_Setting_Gripper(position, rotation, progress2);
            cleanbutton(1);
            rotation2.setBackgroundResource(R.drawable.button13);
        }else if (v.getId() == R.id.disher_record_way_rotation3) {//揽拌子转向：0正方向、1反方向、2周期正反转
            rotation = 2;
            ac.Handing_Setting_Gripper(position, rotation, progress2);
            cleanbutton(1);
            rotation3.setBackgroundResource(R.drawable.button13);
        } else if (v.getId() == R.id.disher_record_cook_box1) {//料盒投放
            if (selectbox == 1){
                String str = ac.CheckIsCanMove("投料");
                Log.d("Manual","str " + str);
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(1,2);
                img2.setImageResource(R.drawable.select);
                box1.setVisibility(View.INVISIBLE);
                box2.setVisibility(View.VISIBLE);
                selectbox = 2;
            }
        }else if (v.getId() == R.id.disher_record_cook_box2) {//料盒投放
            if (selectbox == 2){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(2,2);
                img3.setImageResource(R.drawable.select);
                box2.setVisibility(View.INVISIBLE);
                box3.setVisibility(View.VISIBLE);
                selectbox = 3;
            }
        }else if (v.getId() == R.id.disher_record_cook_box3) {//料盒投放
            if (selectbox == 3){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(3,2);
                img4.setImageResource(R.drawable.select);
                box3.setVisibility(View.INVISIBLE);
                box4.setVisibility(View.VISIBLE);
                selectbox = 4;
            }
        }else if (v.getId() == R.id.disher_record_cook_box4) {//料盒投放
            if (selectbox == 4){
                String str = ac.CheckIsCanMove("投料");
                if (str.length() > 0) {
                    //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this,str);
                    return;
                }
                ac.Handing_Setting_ThrowBox(4,2);
                box4.setVisibility(View.INVISIBLE);
            }
        } else if (v.getId() == R.id.disher_record_way1) {//喷泵
            Log.d("ppp", "way1 clicked");
            ac.Handing_Setting_OpenNozzle(1,2);
        }else if (v.getId() == R.id.disher_record_way2) {//喷泵
            ac.Handing_Setting_OpenNozzle(2,2);
        }else if (v.getId() == R.id.disher_record_way3) {//喷泵
            ac.Handing_Setting_OpenNozzle(3,2);
        }else if (v.getId() == R.id.disher_record_way4) {//喷泵
            ac.Handing_Setting_OpenNozzle(4,2);
        }else if (v.getId() == R.id.disher_record_way5) {//喷泵
            ac.Handing_Setting_OpenNozzle(5,2);
        }else if (v.getId() == R.id.disher_record_way6) {//喷泵
            ac.Handing_Setting_OpenNozzle(6,2);
        } else if (v.getId() == R.id.disher_record_putfood) {//投菜方式
//            Toast.makeText(this, "此功能还在开发中", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, ThrowVegetablesActivity.class);
            intent.putExtra("type",2);
            startActivity(intent);
        } else if (v.getId() == R.id.disher_record_ResetBox) {//料盒复位
            ac.Handing_Setting_ResetBox();
            cleanbutton(4);
            selectbox = 1;
        } else if (v.getId() == R.id.disher_record_work_button1) {//点击开始录制
            int status = ac.box_position_value; // 读取状态
            if(status > 1){
                //Toast.makeText(this, "请将料盒复位", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "请将料盒复位");
            }else {
                setJson();//生成json数据
                boolean result = ac.Developing_Start(root);
                if(result){
                    star_record.setVisibility(View.GONE);
                    end_record.setVisibility(View.VISIBLE);
                    disableLongClickListeners();//移除喷泵长按事件
                    putfood.setOnClickListener(null);//移除投菜方式按钮的点击事件
                    restbox.setOnClickListener(null);//移除料盒复位的点击事件
                    // 启动计时任务
                    seconds = 0; // 重置计时器
                    timerRunnable = new Runnable() {
                        @Override
                        public void run() {
                            seconds++;
                            record_time.setText(seconds + "秒");
                            timerHandler.postDelayed(this, 1000); // 每秒更新一次
                        }
                    };
                    timerHandler.postDelayed(timerRunnable, 1000); // 延迟1秒后开始计时
                }else {
                    //Toast.makeText(this, "录制菜谱失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "录制菜谱失败");
                }
            }
        } else if (v.getId() == R.id.disher_record_work_button2) {//点击结束录制
            if (ac.box_position_value <=4 && ac.box_throw_move == 1){
                // 停止计时任务
                if (timerHandler != null && timerRunnable != null) {
                    timerHandler.removeCallbacks(timerRunnable);
                }
                ac.Developing_Stop();
                //跳转界面
                ac.Handing_Stop();//停止手动炒制
                startActivity(new Intent(this,FinishRecordActivity.class));
                finish();
            }else {
                //Toast.makeText(this, "料盒仍在运动中，请等待", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "料盒仍在运动中，请等待");
            }
        }
    }

    private void startcheak() {
        if (handler != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 执行的任务：读取数据并更新 UI
                    cheak();
                    // 递归调用，实现每秒重复执行
                    handler.postDelayed(this, 1000);
                }
            }, 1000); // 延迟1秒执行
        } else {
            Log.e("ManualCookActivity", "Handler is null in startcheak method");
        }
    }

    @Override
    protected void onDestroy() {
        // 移除所有回调，避免内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        // 移除所有回调，避免内存泄漏
        if (timerHandler != null && timerRunnable != null) {
            timerHandler.removeCallbacks(timerRunnable);
        }
        // 关闭弹窗
        dismissDialog();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void cheak() {
        // 确保在 UI 线程中更新
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int status = ac.handmaster.steep_status; // 读取状态
                Log.d("ManualCookActivity","status: " + status);
                if (ac.pot_temperature_is_error == true){
                    wendu.setVisibility(View.INVISIBLE);
                    error.setVisibility(View.VISIBLE);
                }else {
                    error.setVisibility(View.GONE);
                    wendu.setVisibility(View.VISIBLE);
                    String temperature = String.valueOf(ac.pot_temperature_value); // 读取温度
                    Log.d("wendu", "温度: " + temperature);
                    wendu.setText("锅温：" + temperature + "℃");
                }
                if (status == 0){
//                    if (ac.is_test == true) {
//                        ac.handmaster.Start();
//                        return;
//                    }
                    showDialog();
                } else {
                    dismissDialog();
                }
            }
        });
    }

    private void showDialog() {
        // 如果弹窗已经显示，则不重复显示
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.waitcook, null);
        builder.setView(dialogView);

        // 获取弹窗中的按钮和计时器文本
        final TextView countdownTextView = dialogView.findViewById(R.id.countdownTextView);
        timer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTextView.setText((millisUntilFinished / 1000) + "S");
            }
            @Override
            public void onFinish() {
                // 如果弹窗存在且正在显示，则关闭它
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
                finish();
                //Toast.makeText(DishesRecordActivity.this,"设备就位失败，请重试！",Toast.LENGTH_SHORT).show();
                ToastUtils.show(DishesRecordActivity.this,"设备就位失败，请重试！");
                ac.Handing_Stop();
            }
        };
        timer.start();
        // 创建并显示弹窗
        dialog = builder.create();
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
        // 保存计时器和弹窗引用，以便在状态改变时停止计时器和关闭弹窗
        this.dialog = dialog;
        this.handler = handler;
        this.runnable = runnable;
    }

    // 关闭弹窗
    private void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            if ( timer != null ){
                timer.cancel();
                timer = null;
            }
        }
    }

    //设置按钮样式的方法
    public void cleanbutton(int type){
        if (type == 1){//搅拌爪方向
            rotation1.setBackgroundResource(R.drawable.button14);
            rotation2.setBackgroundResource(R.drawable.button14);
            rotation3.setBackgroundResource(R.drawable.button14);
        } else if (type == 4) {//料盒复位
            img2.setImageResource(R.drawable.noselect);
            img3.setImageResource(R.drawable.noselect);
            img4.setImageResource(R.drawable.noselect);
            box1.setVisibility(View.VISIBLE);
            box2.setVisibility(View.INVISIBLE);
            box3.setVisibility(View.INVISIBLE);
            box4.setVisibility(View.INVISIBLE);
        }
    }

    // 在Activity可见时注册EventBus
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop(){
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    //接受关于机械臂运动状态的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event){
        if (event.id == EventMessage.MSG_ID_OnGripperChange){
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String oldValue = jsonObject.getString("old_value");//旧的状态
                String newValue = jsonObject.getString("new_value");//新的状态
                if (newValue.equals("1")){//放下
                    rotation1.setEnabled(true);
                    rotation2.setEnabled(true);
                    rotation3.setEnabled(true);
                    customSeekBar.setProgress(1);
                    progress2 = 0;
                    rotation1.setBackgroundResource(R.drawable.button13);
                    customSeekBar.setEnabled(true);
                } else if (newValue.equals("2")) {//抬起
                    rotation1.setEnabled(false);
                    rotation2.setEnabled(false);
                    rotation3.setEnabled(false);
                    customSeekBar.setProgress(1);
                    progress2 = 0;
                    rotation1.setBackgroundResource(R.drawable.button14);
                    rotation2.setBackgroundResource(R.drawable.button14);
                    rotation3.setBackgroundResource(R.drawable.button14);
                    customSeekBar.setEnabled(false);
                }
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
            }
        } else if (event.id == EventMessage.MSG_ID_OnPotChange) {
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String newValue = jsonObject.getString("new_value");//新的状态
                switch ( newValue ){
                    case "1"://洗锅位
                        //洗锅位按钮亮起
                        ac.Handing_Setting_PotPosition(1);
                        //顺时针逆时针正反转不能动
                        rotation1.setEnabled(false);
                        rotation2.setEnabled(false);
                        rotation3.setEnabled(false);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button14);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(false);
                        break;
                    case "2"://出菜位
                        //出菜位按钮亮起
                        ac.Handing_Setting_PotPosition(2);
                        //顺时针逆时针正反转不能动
                        rotation1.setEnabled(false);
                        rotation2.setEnabled(false);
                        rotation3.setEnabled(false);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button14);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(false);
                        break;
                    case "3"://炒菜位
                        //炒菜位按钮亮起
                        ac.Handing_Setting_PotPosition(3);
                        //顺时针逆时针正反转可以动
                        rotation1.setEnabled(true);
                        rotation2.setEnabled(true);
                        rotation3.setEnabled(true);
                        customSeekBar.setProgress(1);
                        progress2 = 0;
                        rotation1.setBackgroundResource(R.drawable.button13);
                        rotation2.setBackgroundResource(R.drawable.button14);
                        rotation3.setBackgroundResource(R.drawable.button14);
                        customSeekBar.setEnabled(true);
                        break;
                }

                //手臂状态
                //锁屏按钮消失
                lockBackground.setVisibility(View.GONE);
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
            }
        } else if (event.id == EventMessage.MSG_ID_OnGripperMoving) {
            String jsonString = event.message;
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                String oldValue = jsonObject.getString("old_value");//旧的状态
                String newValue = jsonObject.getString("new_value");//新的状态
                rotation1.setBackgroundResource(R.drawable.button14);
                rotation2.setBackgroundResource(R.drawable.button14);
                rotation3.setBackgroundResource(R.drawable.button14);
                rotation1.setEnabled(false);
                rotation2.setEnabled(false);
                rotation3.setEnabled(false);
                customSeekBar.setProgress(1);
                progress2 = 0;
                customSeekBar.setEnabled(false);
            }catch (JSONException e) {
                e.printStackTrace();
                Log.e("EventBus", "Error parsing JSON: " + e.getMessage());
            }
        }else if (event.id == EventMessage.MSG_ID_OnPotMoving) {
            rotation1.setBackgroundResource(R.drawable.button14);
            rotation2.setBackgroundResource(R.drawable.button14);
            rotation3.setBackgroundResource(R.drawable.button14);
            rotation1.setEnabled(false);
            rotation2.setEnabled(false);
            rotation3.setEnabled(false);
            customSeekBar.setProgress(1);
            progress2 = 0;
            customSeekBar.setEnabled(false);
        }
    }

    //接受粘性事件，当编辑好了喷泵返回的时候重新跟新ui
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) // 添加 sticky 属性
    public void onRefreshEvent(RefreshEvent event) {
        if (event.getEventType() == RefreshEvent.REFRESH_TEXT) {
            Log.d("RefreshEvent", "sucess");
            getJson(); // 获取最新数据
            setview(); // 更新 UI
            // 移除粘性事件（可选）
//            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onDishesRecordEvent(DishesRecordEvent event) {
        // 在这里处理接收到的 JSON 数据
        vegetable_name = event.getFood_name();
        vegetable_copies_qty = event.getFood_num();
        vegetable_weight = event.getFood_weight();
        boxDates = event.getHandingConfigs();
        // 更新 UI 或执行其他操作
        Log.d("DishesRecordActivity", "vegetable_name: " + vegetable_name
                + " vegetable_copies_qty: " + vegetable_copies_qty + " vegetable_weight: " + vegetable_weight + "\nboxDates: " + boxDates);
    }


    @Override
    public boolean onLongClick(View v) {
        if(v.getId() == R.id.disher_record_way1){
            Intent intent = new Intent(this, SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",1);
            intent.putExtra("type",2);
            startActivity(intent);
        } else if (v.getId() == R.id.disher_record_way2) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",2);
            intent.putExtra("type",2);
            startActivity(intent);
        }else if (v.getId() == R.id.disher_record_way3) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",3);
            intent.putExtra("type",2);
            startActivity(intent);
        }else if (v.getId() == R.id.disher_record_way4) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",4);
            intent.putExtra("type",2);
            startActivity(intent);
        }else if (v.getId() == R.id.disher_record_way5) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",5);
            intent.putExtra("type",2);
            startActivity(intent);
        }else if (v.getId() == R.id.disher_record_way6) {
            Intent intent = new Intent(this,SetOilPumpActivity.class);
            intent.putExtra("oil_pump_num",6);
            intent.putExtra("type",2);
            startActivity(intent);
        }
        return true;
    }

    //开始录制时生成json数据
    public void setJson() {
        try {
            // 创建最外层的 JSONObject
            root = new JSONObject();
            root.put("vegetable_name", vegetable_name); // 设置菜谱名称
            root.put("face_image_url", face_image_url);// 设置封面图路径
            JSONArray specDataArray = new JSONArray();// 创建 spec_data 数组
            JSONObject specData = new JSONObject();// 创建 spec_data 的第一个对象
            specData.put("copies_qty", vegetable_copies_qty);
            specData.put("weight", vegetable_weight);
            JSONArray materialDataArray = new JSONArray();// 创建 material_data 数组
            for (BoxDate box : boxDates) {
                JSONObject material = new JSONObject();
                material.put("box_index", box.getBox_index());
                material.put("material_name", box.getMaterial_name());
                material.put("weight", box.getWeight());
                materialDataArray.put(material);
            }
            // 将 material_data 数组添加到 spec_data 对象
            specData.put("material_data", materialDataArray);
            // 将 spec_data 对象添加到 spec_data 数组
            specDataArray.put(specData);
            // 将 spec_data 数组添加到根对象
            root.put("spec_data", specDataArray);
            // 打印生成的 JSON 数据
            Log.d("setJson", "Generated JSON: " + root);
        } catch (Exception e) {
            e.printStackTrace();
            //Toast.makeText(this, "生成 JSON 数据时出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
            ToastUtils.show(this, "生成 JSON 数据时出错: " + e.getMessage());
        }
    }

    //给boxDates数据初始化
    private void setBoxDates() {
        // 创建 BoxDate 对象并添加到列表
        BoxDate box1 = new BoxDate("1", "生姜", "20");
        BoxDate box2 = new BoxDate("2", "", "0");
        BoxDate box3 = new BoxDate("3", "", "0");
        BoxDate box4 = new BoxDate("4", "", "0");
        // 将对象添加到列表
        boxDates.add(box1);
        boxDates.add(box2);
        boxDates.add(box3);
        boxDates.add(box4);
    }

    //移除六个喷泵的
    private void disableLongClickListeners() {
        // 移除六个控件的长按监听器
        way1.setOnLongClickListener(null);
        way2.setOnLongClickListener(null);
        way3.setOnLongClickListener(null);
        way4.setOnLongClickListener(null);
        way5.setOnLongClickListener(null);
        way6.setOnLongClickListener(null);
    }

    // 将 R.drawable.photo1 保存到内部存储并获取文件路径
    private String getDrawablePathFromInternalStorage(int resourceId) {
        // 获取应用上下文
        Context context = getApplicationContext();
        // 定义文件名
        String fileName = "photo1.png";
        // 创建一个文件保存到内部存储
        File file = new File(context.getFilesDir(), fileName);
        // 检查文件是否存在
        if (file.exists()) {
            // 文件已存在，直接返回文件的绝对路径
            return "file://" + file.getAbsolutePath();
        } else {
            // 文件不存在，保存资源文件到内部存储
            try {
                // 打开资源文件的输入流
                InputStream inputStream = getResources().openRawResource(resourceId);
                // 打开文件输出流
                OutputStream outputStream = new FileOutputStream(file);
                // 将资源文件的内容写入到输出流
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                // 关闭流
                outputStream.close();
                inputStream.close();
                // 返回文件的绝对路径
                return "file://" + file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

}